package red.cyq.modules.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import red.cyq.modules.entity.Message;
import red.cyq.modules.entity.User;
import red.cyq.modules.service.MessageServiceImp;
import red.cyq.modules.service.UserServiceImpl;


@Controller
public class IndexController extends BaseController{
	
	@Autowired
	private MessageServiceImp messageService;
	@Autowired
	private UserServiceImpl userService;
	
	@RequestMapping(value={"/tologin" , " " }, method=RequestMethod.GET)
	public String tologin(){
		return "modules/login";
	}
	
	@RequestMapping(value="/login" , method=RequestMethod.POST)
	public String login(User user,HttpSession session,Model modle){
		logger.warn("用户登陆 {}",user.getLoginName() +  user.getPassword());
		String pwd = user.getPassword();
		if((user = userService.getUserByLoginName(user.getLoginName())) == null){
			modle.addAttribute("message", "用户名或密码错误！");
			return "modules/login";
		}
		if(!user.getPassword().equals(pwd)){
			modle.addAttribute("message", "用户名或密码错误！");
			return "modules/login";
		}
		session.setAttribute(User.USER_SESSION, user);
		return "modules/index";
	}
	
	@RequestMapping("tomessage")
	public String tomessage(){
		return "modules/tomessage";
	}
	
	@RequestMapping("savemessage")
	public String savemessage(Message message,Model model,HttpServletRequest request){
		message.setRemoteAddr(request.getRemoteAddr());
		System.out.println("昵称" + message.getName());
		System.out.println("邮箱" + message.getEmail());
		System.out.println("留言信息" + message.getMessage());
		System.out.println("主题" + message.getSelection());
		System.out.println("ip: " + request.getRemoteAddr());
		messageService.add(message);
		model.addAttribute("message", "留言成功！");
		return "modules/tomessage";
	}
	
	@RequestMapping("logout")
	public String logout(HttpServletRequest request){
		User user = (User) request.getSession().getAttribute(User.USER_SESSION);
		if (user != null) {
			request.getSession().removeAttribute(User.USER_SESSION);
			logger.info("用户退出  {}","用户名：" + user.getLoginName());
		}
		return "modules/login";
	}
}
